package com.nsgf.library.ui.page;

import android.content.Intent;
import android.os.Bundle;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.DutyManagerBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityPersonnelSelectionBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.adapter.PersonnelListAdapter;

import android.os.Handler;
import android.os.Looper;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 人员选择页面
 */
public class PersonnelSelectionActivity extends BaseActivity {

    PersonnelSelectionStates states;
    private ActivityPersonnelSelectionBinding mBinding;
    private AccountRequester mAccountRequester;
    private PersonnelListAdapter mAdapter;
    private String selectionType; // 标识是选择人员还是领导
    private boolean isSingleMode = false; // 是否为单选模式
    private Handler mainHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void initViewModel() {
        states = getActivityScopeViewModel(PersonnelSelectionStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        // 这里先创建一个空的adapter，稍后在onCreate中会重新创建
        mAdapter = new PersonnelListAdapter(
                this,
                new ArrayList<>(),
                new ArrayList<>(),
                item -> {
                    // 临时处理，稍后会被替换
                }
        );

        return new DataBindingConfig(R.layout.activity_personnel_selection, BR.vm, states)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.adapter, mAdapter);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityPersonnelSelectionBinding) getBinding();

        // 获取传递的参数
        if (getIntent() != null) {
            selectionType = getIntent().getStringExtra("selectionType");

            // 判断是否为单选模式（交班领导、值班领导、接班领导）
            isSingleMode = "handoverLeader".equals(selectionType) ||
                    "dutyLeader".equals(selectionType) ||
                    "receivingLeader".equals(selectionType);
            mAdapter.setSingleSelectionMode(isSingleMode);

            // 获取预先选择的人员对象列表（用于回显）
            @SuppressWarnings("unchecked")
            ArrayList<DutyManagerBean.BuSchedulingListBean> preselectedItems =
                    (ArrayList<DutyManagerBean.BuSchedulingListBean>) getIntent().getSerializableExtra("preselectedItems");
            if (preselectedItems != null && !preselectedItems.isEmpty()) {
                // 如果是单选模式且有多项，只保留第一项
                if (isSingleMode && preselectedItems.size() > 1) {
                    ArrayList<DutyManagerBean.BuSchedulingListBean> singleItem = new ArrayList<>();
                    singleItem.add(preselectedItems.get(0));
                    states.selectedItems.set(singleItem);
                    android.util.Log.d("PersonnelSelection", "单选模式：从" + preselectedItems.size() + "项中只保留第一项");
                } else {
                    // 保存预先选中的对象列表
                    states.selectedItems.set(new ArrayList<>(preselectedItems));
                }
                android.util.Log.d("PersonnelSelection", "接收到的预先选中项数量: " + states.selectedItems.get().size());
            }

            // 获取预先选择的人员显示名称（用于显示）
            String preselectedNames = getIntent().getStringExtra("preselectedNames");
            if (preselectedNames != null && !preselectedNames.isEmpty()) {
                android.util.Log.d("PersonnelSelection", "接收到的预先选中名称: " + preselectedNames);
                // 如果需要显示在页面上，可以在这里设置到State中
                // 例如：states.preselectedNames.set(preselectedNames);
            }
        }
        mAdapter.setOnItemClickListener(new BaseDataBindingAdapter.OnItemClickListener<DutyManagerBean.BuSchedulingListBean>() {
            @Override
            public void onItemClick(int viewId, DutyManagerBean.BuSchedulingListBean item, int position) {
                if (item == null) {
                    android.util.Log.e("PersonnelSelection", "onItemClick: item is null");
                    return;
                }

                int userId = item.getUserId();
                android.util.Log.d("PersonnelSelection", "onItemClick: userId=" + userId + ", position=" + position);

                // 使用适配器的toggleSelection方法切换选中状态（使用userId作为唯一标识）
                mAdapter.toggleSelection(item);

                // 同步更新states中的selectedItems列表（用于回传完整对象）
                List<DutyManagerBean.BuSchedulingListBean> currentList = states.personnelList.get();
                List<DutyManagerBean.BuSchedulingListBean> selectedItems = new ArrayList<>();
                if (currentList != null) {
                    Set<Integer> selectedIds = mAdapter.getSelectedIds();
                    android.util.Log.d("PersonnelSelection", "selectedIds after toggle: " + selectedIds);
                    for (DutyManagerBean.BuSchedulingListBean bean : currentList) {
                        if (bean != null) {
                            // 比较接口返回的id和选中的id
                            Object beanId = bean.getId();
                            if (beanId != null) {
                                int idValue = 0;
                                if (beanId instanceof Integer) {
                                    idValue = (Integer) beanId;
                                } else if (beanId instanceof Double) {
                                    idValue = ((Double) beanId).intValue();
                                } else if (beanId instanceof String) {
                                    try {
                                        idValue = Integer.parseInt((String) beanId);
                                    } catch (NumberFormatException e) {
                                        continue;
                                    }
                                }
                                if (idValue > 0 && selectedIds.contains(idValue)) {
                                    selectedItems.add(bean);
                                }
                            }
                        }
                    }
                    android.util.Log.d("PersonnelSelection", "selectedItems count: " + selectedItems.size());
                }
                states.selectedItems.set(selectedItems);
                updateConfirmButton();
            }
        });

        initTitleBar();
        initRecyclerView();
        loadPersonnelList();

        // 注册人员列表数据监听
        getLifecycle().addObserver(mAccountRequester);
        mAccountRequester.getPersonnelListResult().observe(this, responseStatus -> {
            if (responseStatus.isSuccess()) {
                if (responseStatus.getResponseCode() == 200) {
                    List<DutyManagerBean.BuSchedulingListBean> personnelList = responseStatus.getData();
                    if (personnelList != null) {
                        // 先设置预先选择的人员（回显已选中的人员）
                        List<DutyManagerBean.BuSchedulingListBean> preselectedItems = states.selectedItems.get();
                        List<DutyManagerBean.BuSchedulingListBean> matchedItems = new ArrayList<>();

                        if (preselectedItems != null && !preselectedItems.isEmpty()) {
                            // 根据传入的id和userId与接口返回的id和userId进行比较匹配
                            Set<Integer> preselectedIds = new HashSet<>();
                            Set<Integer> preselectedUserIds = new HashSet<>();

                            // 提取预先选中的id和userId（传入数据）
                            android.util.Log.d("PersonnelSelection", "开始匹配预设项，预设项数量: " + preselectedItems.size());
                            for (DutyManagerBean.BuSchedulingListBean preselected : preselectedItems) {
                                if (preselected != null) {
                                    // 提取userId
                                    int userId = preselected.getUserId();
                                    if (userId > 0) {
                                        preselectedUserIds.add(userId);
                                    }
                                    
                                    // 提取id（Object类型，可能是Integer、Double或String）
                                    Object preselectedId = preselected.getId();
                                    if (preselectedId != null) {
                                        int idValue = 0;
                                        if (preselectedId instanceof Integer) {
                                            idValue = (Integer) preselectedId;
                                        } else if (preselectedId instanceof Double) {
                                            idValue = ((Double) preselectedId).intValue();
                                        } else if (preselectedId instanceof String) {
                                            try {
                                                idValue = Integer.parseInt((String) preselectedId);
                                            } catch (NumberFormatException e) {
                                                // 忽略转换失败的情况
                                            }
                                        }
                                        if (idValue > 0) {
                                            preselectedIds.add(idValue);
                                        }
                                    }
                                    android.util.Log.d("PersonnelSelection", "预设项 - userId: " + userId + ", id: " + preselectedId);
                                }
                            }
                            android.util.Log.d("PersonnelSelection", "提取的preselectedIds: " + preselectedIds + ", preselectedUserIds: " + preselectedUserIds);

                            // 在personnelList中查找匹配的项（比较传入的id/userId和接口返回的id/userId）
                            android.util.Log.d("PersonnelSelection", "开始遍历接口返回的人员列表，数量: " + personnelList.size());
                            for (DutyManagerBean.BuSchedulingListBean bean : personnelList) {
                                if (bean != null) {
                                    // 接口返回的id（Object类型，可能是Integer、Double或String）
                                    Object beanId = bean.getId();
                                    int beanUserId = bean.getUserId();
                                    android.util.Log.d("PersonnelSelection", "检查项 - userId: " + beanUserId + ", id: " + beanId + " (type: " + (beanId != null ? beanId.getClass().getSimpleName() : "null") + ")");

                                    boolean isMatched = false;
                                    
                                    // 方法1：比较id
                                    if (beanId != null) {
                                        int idValue = 0;
                                        // 将id转换为整数进行比较（支持Integer、Double、String类型）
                                        if (beanId instanceof Integer) {
                                            idValue = (Integer) beanId;
                                        } else if (beanId instanceof Double) {
                                            idValue = ((Double) beanId).intValue();
                                        } else if (beanId instanceof String) {
                                            try {
                                                idValue = Integer.parseInt((String) beanId);
                                            } catch (NumberFormatException e) {
                                                android.util.Log.w("PersonnelSelection", "无法解析id: " + beanId);
                                            }
                                        }
                                        
                                        if (idValue > 0 && preselectedIds.contains(idValue)) {
                                            isMatched = true;
                                            android.util.Log.d("PersonnelSelection", "✓ 通过id匹配成功: 传入id=" + idValue + ", 接口返回id=" + beanId);
                                        }
                                    }
                                    
                                    // 方法2：如果id匹配失败，尝试用userId匹配
                                    if (!isMatched && beanUserId > 0 && preselectedUserIds.contains(beanUserId)) {
                                        isMatched = true;
                                        android.util.Log.d("PersonnelSelection", "✓ 通过userId匹配成功: userId=" + beanUserId);
                                    }
                                    
                                    // 方法3：如果前两种都失败，尝试用接口返回的id匹配传入的userId
                                    if (!isMatched && beanId != null) {
                                        int idValue = 0;
                                        if (beanId instanceof Integer) {
                                            idValue = (Integer) beanId;
                                        } else if (beanId instanceof Double) {
                                            idValue = ((Double) beanId).intValue();
                                        } else if (beanId instanceof String) {
                                            try {
                                                idValue = Integer.parseInt((String) beanId);
                                            } catch (NumberFormatException e) {
                                                // 忽略
                                            }
                                        }
                                        if (idValue > 0 && preselectedUserIds.contains(idValue)) {
                                            isMatched = true;
                                            android.util.Log.d("PersonnelSelection", "✓ 通过id匹配userId成功: 接口返回id=" + idValue + ", 传入userId包含此值");
                                        }
                                    }
                                    
                                    if (isMatched) {
                                        matchedItems.add(bean);
                                    } else if (beanId == null) {
                                        android.util.Log.w("PersonnelSelection", "接口返回项的id为null，userId: " + beanUserId);
                                    }
                                }
                            }

                            android.util.Log.d("PersonnelSelection", "匹配完成 - 匹配到的预先选中项数量: " + matchedItems.size() + ", 原始数量: " + preselectedItems.size());

                            // 如果是单选模式且匹配到多项，只保留第一项
                            if (isSingleMode && matchedItems.size() > 1) {
                                List<DutyManagerBean.BuSchedulingListBean> singleItem = new ArrayList<>();
                                singleItem.add(matchedItems.get(0));
                                matchedItems = singleItem;
                                android.util.Log.d("PersonnelSelection", "单选模式：只保留第一项");
                            }

                            // 更新states
                            states.selectedItems.set(matchedItems);

                            // 在设置列表之前先更新适配器的选中状态
                            if (!matchedItems.isEmpty()) {
                                android.util.Log.d("PersonnelSelection", "准备更新选中状态，匹配项数量: " + matchedItems.size());
                                for (DutyManagerBean.BuSchedulingListBean matchedItem : matchedItems) {
                                    Object itemId = matchedItem.getId();
                                    android.util.Log.d("PersonnelSelection", "匹配项信息 - userId: " + matchedItem.getUserId() + ", id: " + itemId);
                                }
                                mAdapter.updateSelectedItems(matchedItems);
                                android.util.Log.d("PersonnelSelection", "已更新适配器选中状态，selectedIds: " + mAdapter.getSelectedIds());
                            } else {
                                android.util.Log.w("PersonnelSelection", "警告：匹配到的项为空！");
                            }
                        }

                        // 设置personnelList（布局中的submitList绑定会自动调用submitList）
                        // 这里设置会触发布局中的submitList绑定，导致列表更新
                        states.personnelList.set(personnelList);

                        // 使用RecyclerView的post方法确保在视图渲染完成后更新选中状态
                        final List<DutyManagerBean.BuSchedulingListBean> finalMatchedItems = matchedItems;
                        if (mBinding.recyclerView != null && finalMatchedItems != null && !finalMatchedItems.isEmpty()) {
                            mBinding.recyclerView.post(() -> {
                                if (mAdapter != null) {
                                    android.util.Log.d("PersonnelSelection", "RecyclerView post后刷新选中状态，选中项数量: " + finalMatchedItems.size());
                                    // 再次更新以确保状态正确
                                    mAdapter.updateSelectedItems(finalMatchedItems);
                                    // 强制刷新所有item
                                    mAdapter.notifyDataSetChanged();
                                }
                            });

                            // 额外的延迟作为备用方案
                            mainHandler.postDelayed(() -> {
                                if (mAdapter != null && !finalMatchedItems.isEmpty()) {
                                    android.util.Log.d("PersonnelSelection", "延迟刷新选中状态（备用），选中项数量: " + finalMatchedItems.size());
                                    mAdapter.updateSelectedItems(finalMatchedItems);
                                    mAdapter.notifyDataSetChanged();
                                }
                                updateConfirmButton();
                            }, 500);
                        } else {
                            updateConfirmButton();
                        }
                    }
                } else {
                    showToast(responseStatus.getMsg());
                }
            }
        });
    }

    /**
     * 初始化标题栏
     */
    private void initTitleBar() {
        String title = "值班记录";
        if ("leader".equals(selectionType)) {
            title = "值班记录";
        } else if ("person".equals(selectionType)) {
            title = "值班记录";
        }
        states.titleBar.set(title);
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        // Adapter已在getDataBindingConfig中初始化
    }

    /**
     * 加载人员列表
     */
    private void loadPersonnelList() {
        // 获取项目编码，调用API获取人员列表
        mAccountRequester.getPersonnelList();
    }

    /**
     * 更新确认按钮状态
     */
    private void updateConfirmButton() {
        int selectedCount = states.selectedItems.get().size();
        states.confirmButtonText.set(selectedCount > 0 ? "确定(" + selectedCount + ")" : "确定");
    }

    /**
     * 返回选中的结果
     */
    private void confirmSelection() {
        List<DutyManagerBean.BuSchedulingListBean> selectedItems = states.selectedItems.get();

        Intent result = new Intent();
        result.putExtra("selectedItems", new ArrayList<>(selectedItems));
        result.putExtra("selectionType", selectionType);

        // 构造选中人员的名称字符串
        if (!selectedItems.isEmpty()) {
            StringBuilder names = new StringBuilder();
            for (int i = 0; i < selectedItems.size(); i++) {
                if (i > 0) names.append(",");
                names.append(selectedItems.get(i).getRealName());
            }
            result.putExtra("selectedNames", names.toString());
        }

        setResult(RESULT_OK, result);
        finish();
    }

    /**
     * 取消选择
     */
    private void cancelSelection() {
        setResult(RESULT_CANCELED);
        finish();
    }

    public class ClickProxy {
        /**
         * 取消按钮
         */
        public void onCancelClick() {
            cancelSelection();
        }

        /**
         * 确定按钮
         */
        public void onConfirmClick() {
            confirmSelection();
        }
    }

    public static class PersonnelSelectionStates extends StateHolder {
        public final State<String> titleBar = new State<>("值班记录");
        public final State<String> confirmButtonText = new State<>("确定");
        public final State<List<DutyManagerBean.BuSchedulingListBean>> personnelList = new State<>(new ArrayList<>());
        public final State<List<DutyManagerBean.BuSchedulingListBean>> selectedItems = new State<>(new ArrayList<>());
    }
}

